package com.littleken.foodieApi.controller;

import com.littleken.foodieCommon.Response.ErrorCode;
import com.littleken.foodieCommon.Response.ServerResponse;
import com.littleken.foodieCommon.enums.OrderStatusEnum;
import com.littleken.foodieCommon.enums.PayMethodEnum;
import com.littleken.foodiePojo.bo.SubmitOrderBO;
import com.littleken.foodiePojo.vo.MerchantOrdersVO;
import com.littleken.foodiePojo.vo.OrderVO;
import com.littleken.foodieService.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * Create by littleken on 2020/11/26 9:52
 */
@RequestMapping("orders")
@RestController
public class OrdersController {

    final static Logger logger = LoggerFactory.getLogger(OrdersController.class);

    @Resource
    private OrderService orderService;

    @PostMapping("/create")
    public ServerResponse create(
            @RequestBody SubmitOrderBO submitOrderBO,
            HttpServletRequest request,
            HttpServletResponse response) {
        if (PayMethodEnum.getEnumByCode(submitOrderBO.getPayMethod()) == null) {
            return ServerResponse.fail(ErrorCode.ERROR_PAYMETHOD);
        }
        OrderVO orderVO = orderService.createOrder(submitOrderBO);
        String orderId = orderVO.getOrderId();

        // 3. 向支付中心发送当前订单，用于保存支付中心的订单数据
        MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
        String payReturnUrl = "127.0.0.1/foodie/orders/notifyMerchantOrderPaid/";
        //本系统回调地址
        merchantOrdersVO.setReturnUrl(payReturnUrl);
        merchantOrdersVO.setAmount(1);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId","imooc");
        headers.add("password","imooc");

        //向支付中心发请求
        HttpEntity<MerchantOrdersVO> entity =
                new HttpEntity<>(merchantOrdersVO, headers);

        //支付中心支付url
        String paymentUrl = "";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<ServerResponse> responseEntity =
                restTemplate.postForEntity(paymentUrl,
                        entity,
                        ServerResponse.class);
        ServerResponse paymentResult = responseEntity.getBody();
        if (paymentResult.getErrcode() != 200) {
            logger.error("发送错误：{}", paymentResult.getDetailErrMsg());
            return ServerResponse.fail(ErrorCode.ERROR_PAYMETHOD);
        }
        return ServerResponse.success(orderId);
    }

    /**
     * 异步回调支付情况
     *
     * @param merchantOrderId
     * @return
     */
    @PostMapping("notifyMerchantOrderPaid/{merchantOrderId}")
    public Integer notifyMerchantOrderPaid(@PathVariable String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.getCode());
        return HttpStatus.OK.value();
    }

    @PostMapping("getPaidOrderInfo")
    public ServerResponse getPaidOrderInfo(String orderId) {
        return ServerResponse.success();
    }

    @PostMapping("/pending/{userId}")
    public ServerResponse pending(@PathVariable String userId){
        return ServerResponse.success();
    }
}
